#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>

using namespace std;

/* 错误码 */
int g_exitStatus = -1;

int main()
{
#if 0
    pid_t pid = getpid();
    /* 父进程ID号 */
    pid_t ppid = getppid();
    cout << "pid:"<< pid <<endl;
    cout <<"ppid:"<<ppid<<endl;

    int cnt = 60;
    while(cnt--)
    {
        sleep(1);
    }
#endif

    int val = 100;
    /* vfork : create child process and block parent process */
    pid_t pid = fork();
    if(pid == -1)
    {
        perror("fork error\n");
        exit(-1);
    }
    else if(pid ==0 )
    {
        sleep(3);
        
        cout << "child process" <<endl;
        cout << "child process pid:" << getpid() <<endl;
        cout << "child process parent pid:" << getppid() <<endl;

        /* 退出进程 */
     
        _exit(g_exitStatus);

        const char *filename = "./1.txt";
        // char buffer[128] = {0};
        // int fd = open(filename,O_RDONLY);
        //read(fd,&val,sizeof(int));
        // val = atoi(buffer);
        cout << "child val:" << val <<endl;
        int fd = open(filename,O_CREAT | O_WRONLY,0644);
        // write(fd,buffer,strlen(buffer));
        // cout << "buffer:" <<buffer <<endl;
        int writeBytes = write(fd,(const void*)&val,sizeof(int));

        //close(fd);

    }
    else
    {
        int childStatus = 0;
        // wait(&childStatus); //阻塞

        waitpid(pid,&childStatus,0);
        cout << "childStatus:" << childStatus << endl;
        cout << " WIFSIGNALED(wstatus):" <<  WIFSIGNALED(childStatus) <<endl;

        cout <<" parent pid:" << pid <<endl;
        cout << "parent process" <<endl;
        cout << "parent process pid:" << getpid() <<endl;

        cout << "parent val:" << val <<endl;
        val += 10000;
        cout << "parent val:" << val <<endl;

        /* 父进程写数据 */
        const char *filename = "./1.txt";
        // char buffer[128] = {0};
        // sprintf(buffer,"%d",val);
        int fd = open(filename,O_CREAT | O_WRONLY,0644);
        // write(fd,buffer,strlen(buffer));
        // cout << "buffer:" <<buffer <<endl;
        int writeBytes = write(fd,(const void*)&val,sizeof(int));
        //close(fd);
    }

    cout<< "hello world" <<endl;

    int cnt = 10;
    while(cnt--)
    {
        sleep(1);
    }


    return 0;
}